package com.csoa.community.requests;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.chinaface.JSONArray;
import org.json.chinaface.JSONObject;

import android.content.Context;
import android.util.Log;

import com.csoa.community.activity.BaseActivity.OnUICallback;
import com.csoa.community.bean.LinkmanModel;
import com.csoa.community.net.ErrorMsg;
import com.csoa.community.net.WcfAsyncTask;
import com.csoa.community.utils.AndroidUtils;
import com.csoa.community.utils.PinYinHelper;
import com.csoa.community.utils.StringUtils;

public class LinkmanRequest extends AbstractRequest {

	public static List<List<LinkmanModel>> users;
	public static List<String> buMens;
	Context cxt;
	static boolean isBumen;
	
	public LinkmanRequest(List<BasicNameValuePair> requestValues, Context cxt, boolean isBumen) {
		super(isBumen ? method_linkman : method_linkman_group, requestValues);
		this.cxt = cxt;
		LinkmanRequest.isBumen = isBumen;
	}

	@Override
	protected void parseRemaingInfo(String json) throws ErrorMsg {
		
		cacheResult(json, isBumen, false, cxt);
		
		parseData(json);
	}
	
	public static void parseData(String json)  throws ErrorMsg {
		if(!StringUtils.isEmpty(json)) {
			
			users = new ArrayList<List<LinkmanModel>>();
			buMens = new ArrayList<String>();
			
			if (isBumen) {
				parseDataByBumen(json);
			} else {
				parseDataByZu(json);
			}
		}
	}
	
	private static void parseDataByBumen(String json) {
		try {
			JSONArray ja = new JSONArray(json);
			LinkmanModel user;
			JSONObject jb;
			for (int i = 0; i < ja.length(); i++) {
				user = new LinkmanModel();
				jb = ja.getJSONObject(i);
				Log.e("", jb.toString());
				user.id = jb.getString("GUID");
				user.name = jb.getString("DisName");
				user.namePY = jb.getString("LogName");
				user.buMen = jb.getString("OU");
				user.SortID = jb.getString("SortID");
				user.SortOU = jb.getString("SortOU");
				user.status = jb.getString("status");
				user.SortIndex = jb.getString("SortIndex");
				
				user.py = PinYinHelper.getPinYinHeadChar(user.name).toCharArray();
				
				if (buMens.contains(user.buMen)) {
					if(buMens.indexOf(user.buMen) < users.size()) {
						users.get(buMens.indexOf(user.buMen)).add(user);
					}
				} else {
					buMens.add(user.buMen);
					users.add(new ArrayList<LinkmanModel>());
					users.get(users.size() - 1).add(user);
				}
				
			}
		} catch (org.json.chinaface.JSONException e) {
			e.printStackTrace();
		}
	}
	private static void parseDataByZu(String json) {
		try {
			JSONArray ja = new JSONArray(json);
			LinkmanModel user;
			JSONObject jb;
			for (int i = 0; i < ja.length(); i++) {
				user = new LinkmanModel();
				jb = ja.getJSONObject(i);
				Log.e("", jb.toString());
				user.id = jb.getString("GUID");
				user.name = jb.getString("DisName");
				user.namePY = jb.getString("LogName");
				user.buMen = jb.getString("ou");
				
				user.py = PinYinHelper.getPinYinHeadChar(user.name).toCharArray();
				
				if (buMens.contains(user.buMen)) {
					users.get(buMens.indexOf(user.buMen)).add(user);
				} else {
					buMens.add(user.buMen);
					users.add(new ArrayList<LinkmanModel>());
					users.get(users.size() - 1).add(user);
				}
				
			}
		} catch (org.json.chinaface.JSONException e) {
			e.printStackTrace();
		}
	}
	
	private final static String cache_file_name_bumen = "cache_file_name_LinkmanRequest_bumen";
	private final static String cache_file_name_zu = "cache_file_name_LinkmanRequest_zu";
	private final static String cache_file = "cache_file";
	private final static String cache_tongbu_time = "cache_tongbu_time";
	private final static String cache_tongbu_jiange_time = "cache_tongbu_jiange_time";
	
	/**
	 * 是否已缓存联系人内容
	 * @return true缓存，false未缓存
	 */
	public static boolean isCache(Context cxt, boolean isBumen) {
		return StringUtils.isNotEmpty(AndroidUtils.getGlobal(cache_file, isBumen ? cache_file_name_bumen : cache_file_name_zu, cxt));
	}
	
	/**
	 * 缓存联系人内容
	 * @param str 需缓存的内容
	 * @param isForce 是否强制重新缓存
	 */
	public static void cacheResult(String str, Boolean isBumen, boolean isForce, Context cxt) {
		
		if ((StringUtils.isEmpty(str) || isCache(cxt, isBumen)) && !isForce) {
			return;
		}
		
		if (isForce) {
			AndroidUtils.removeGlobal(cache_file, isBumen ? cache_file_name_bumen : cache_file_name_zu, cxt);
		}
		initTongBuTime(cxt);
		AndroidUtils.setGlobal(cache_file, isBumen ? cache_file_name_bumen : cache_file_name_zu, str, cxt);
	}
	
	public static void parseCacheData(Context cxt, boolean isBumen) {
		try {
			LinkmanRequest.isBumen = isBumen;
			parseData(AndroidUtils.getGlobal(cache_file, isBumen ? cache_file_name_bumen : cache_file_name_zu, cxt));
		} catch (ErrorMsg e) {
			e.printStackTrace();
		}
	}
	
	public static void tryDoTongBu(final Context cxt) {
		Log.e("onStart", "服务正在启动，这里尝试同步联系人");
		if(isDoTongBu(cxt)) {
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			new WcfAsyncTask(cxt, new OnUICallback() {
				@Override
				public void onGetResult(AbstractRequest request) {
					List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
					new WcfAsyncTask(cxt, new OnUICallback() {
						@Override
						public void onGetResult(AbstractRequest request) {
						}

						@Override
						public void onCancel() {

						}

						@Override
						public void onProgress(int progress, String msg) {
						}
					}).execute(new LinkmanRequest(params, cxt, true));
				}

				@Override
				public void onCancel() {

				}

				@Override
				public void onProgress(int progress, String msg) {
				}
			}).execute(new LinkmanRequest(params, cxt, false));
		}
	}
	
	public static boolean isDoTongBu(Context cxt) {
		long time = getTongBuTime(cxt);
		if(time <= 0) {
			return true;
		}
		int a = AndroidUtils.getSelectDataToNow(time);
		int b = (getTongBuJianGe(cxt) * 7);
//		Log.e("", "a:" + a + " b:" + b + " time:" + time);
		if (a > b) {
			return true;
		}
		return false;
	}
	
	public static void setTongBuJianGe(Context cxt, int date) {
		AndroidUtils.setGlobal(cache_file, cache_tongbu_jiange_time, date + "", cxt);
	}
	
	public static int getTongBuJianGe(Context cxt) {
		String str = AndroidUtils.getGlobal(cache_file, cache_tongbu_jiange_time, cxt);
		if (StringUtils.isEmpty(str)) {
			setTongBuJianGe(cxt, 4);
			return 0;
		} else {
			return Integer.parseInt(str);
		}
	}
	
	public static void initTongBuTime(Context cxt) {
		AndroidUtils.setGlobal(cache_file, cache_tongbu_time, System.currentTimeMillis() + "", cxt);
	}
	
	public static long getTongBuTime(Context cxt) {
		String str = AndroidUtils.getGlobal(cache_file, cache_tongbu_time, cxt);
		if (StringUtils.isEmpty(str)) {
			return 0;
		} else {
			return Long.parseLong(str);
		}
	}
	
}
